<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Silex\Application;

use models\Weixin;
use models\WxSDK;
use utils\out;

//Request::setTrustedProxies(array('127.0.0.1'));

function encodeURIComponent($str) {
    $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
    return strtr(rawurlencode($str), $revert);
}

/** oauth **/
$app->get('/oauth', function (Application $app, Request $request) {
    $appid = $request->get('appid');
    $scope = $request->get('scope');

    if(empty($appid) || empty($scope)) {
        return $app->json(array("success"=>false, "result"=> "oauth failed, invalid params"));
    }
    $redirect = encodeURIComponent(C_REDIRECT);

    return $app->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect&response_type=code&scope=$scope&state=STATE#wechat_redirect");
});

/** redirect **/
$app->get('/redirect', function (Application $app, Request $request) {
    $code = $request->get('code');
    if(empty($code)) {
        return $app->json(array("success"=>false, "result"=> "oauth code required"));
    }

    // 获取access_token
    $data = Weixin::getAccessToken($code);
    if(!empty($data->errmsg)) {
    	return $app->json(array("success"=>false, "result"=> $data->errmsg));
    }

    $accessToken = $data->access_token;
    $openid = $data->openid;

    // 获取用户基本信息
    $data = Weixin::getUserinfo($accessToken, $openid);
	if(!empty($data->errmsg)) {
    	return $app->json(array("success"=>false, "result"=> $data->errmsg));
    }

    $nickname = $data->nickname;
    $avatar = $data->headimgurl;

    return $app->redirect(C_DOMAIN. "?openid=$openid&nickname=$nickname&avatar=$avatar");
});


/**获取jsticket 临时票据**/
$app->get('/wx/jsconfig', function (Application $app, Request $request) {
    $url = $request->get('u');
    $wxsdk = new WxSDK(C_APPID, C_APPSECRET, $url);
    $result = $wxsdk->getSignPackage();
    return $app->json($result, 200);
});
